package com.buddies.lottery.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.os.CountDownTimer;
import android.support.v7.widget.AppCompatTextView;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.widget.TextView;

import com.buddies.lottery.R;
import com.buddies.lottery.data.bean.Lottery;
import com.buddies.lottery.data.bean.LotteryRule;
import com.buddies.lottery.utils.DateUtils;
import com.buddies.lottery.utils.LotteryUtils;

import java.util.List;

public class CountDownTimerView extends AppCompatTextView {

    private Context mContext;

    private CharSequence mPrefixText;
    private CharSequence mSuffixText;

    private long mMilliSeconds = 0;

    private TimerListener mListener;

    private CountDownTimer mCountDownTimer;

    private TextView bindPeriod;
    private TextView bindStatus;

    private Lottery mLottery;

    public CountDownTimerView(Context context) {
        this(context, null);
    }

    public CountDownTimerView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CountDownTimerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;

        init(attrs, defStyleAttr);
    }

    private void init(AttributeSet attrs, int defStyleAttr) {
        TypedArray a = mContext.obtainStyledAttributes(attrs, R.styleable.CountDownTimerView, defStyleAttr, 0);

        if (a != null) {
            mPrefixText = a.getString(R.styleable.CountDownTimerView_prefixText);
            mSuffixText = a.getString(R.styleable.CountDownTimerView_suffixText);
            mMilliSeconds = a.getInt(R.styleable.CountDownTimerView_timeMilliSeconds, 0);
            a.recycle();
        }

//        setTime(null, mMilliSeconds);
//        startCountDown();

        displayText();
    }

    private void initCounter() {
        mCountDownTimer = new CountDownTimer(mMilliSeconds, 500) {
            @Override
            public void onTick(long millisUntilFinished) {
                calculateTime(millisUntilFinished);
                if (mListener != null) {
                    mListener.onTick(millisUntilFinished);
                }
            }

            @Override
            public void onFinish() {
                calculateTime(0);
                if (mListener != null) {
                    mListener.onFinish();
                }

                if (mLottery != null) {
                    int seconds = 0;
                    List<LotteryRule> rules = mLottery.rules;
                    if (rules != null && !rules.isEmpty()) {
                        for (int i = 0; i < rules.size(); i++) {
                            LotteryRule rule = rules.get(i);
                            if (rule.isInRuleTime()) {
                                seconds = rule.getDuration();
                                break;
                            }
                        }
                    }

                    if (seconds > 0) {
                        if (mLottery.next != null) {
                            String period = mLottery.next.period_show;
                            if (!TextUtils.isEmpty(period) && TextUtils.isDigitsOnly(period)) {
                                period = String.valueOf(Long.parseLong(period) + 1);

                                mLottery.next.period_show = period;
                                if (bindPeriod != null) {
                                    bindPeriod.setText(LotteryUtils.formatLotteryNextPeriod(period));
                                }
                            }
                        }

                        mMilliSeconds = seconds * 1000;
                        initCounter();
                        startCountDown();
                    }
                }
            }
        };
    }

    public void startCountDown() {
        if (mCountDownTimer != null) {
            mCountDownTimer.start();
        }
    }

    public void stopCountDown() {
        if (mCountDownTimer != null) {
            mCountDownTimer.cancel();
        }
    }

    public void setPrefixText(CharSequence text) {
        mPrefixText = text;
        displayText();
    }

    public void setSuffixText(CharSequence text) {
        mSuffixText = text;
        displayText();
    }

    public void setTime(Lottery lottery, long milliSeconds) {
        if (lottery != null) {
            mLottery = lottery;
        }
        mMilliSeconds = milliSeconds * 1000;
        stopCountDown();
        initCounter();
        calculateTime(mMilliSeconds);
    }

    private void calculateTime(long milliSeconds) {
        mMilliSeconds = milliSeconds;
        displayText();
    }

    private void displayText() {
        StringBuffer buffer = new StringBuffer();
        if (!TextUtils.isEmpty(mPrefixText)) {
            buffer.append(mPrefixText);
            buffer.append(" ");
        }

        long seconds = mMilliSeconds / 1000;
        long blockTime = getLotteryBlockTime();
        if (seconds > blockTime) {
            seconds = seconds - blockTime;
            if (bindStatus != null) {
                bindStatus.setText("截止封盘");
                bindStatus.setSelected(false);
            }
        } else {
            if (bindStatus != null) {
                bindStatus.setText("已封盘");
                bindStatus.setSelected(true);
            }
        }

        buffer.append(DateUtils.formatDuration(seconds));

        if (!TextUtils.isEmpty(mSuffixText)) {
            buffer.append(" ");
            buffer.append(mSuffixText);
        }

        setText(buffer);
    }

    private long getLotteryBlockTime() {
        return mLottery != null ? mLottery.block_time : 60;
    }

    public void bindView(TextView period, TextView status) {
        bindPeriod = period;
        bindStatus = status;
    }

    public void setOnTimerListener(TimerListener listener) {
        mListener = listener;
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        stopCountDown();
    }

    public interface TimerListener {
        void onTick(long millisUntilFinished);

        void onFinish();
    }

}